/**
 * 广告sdk & 网络控制
 * ts 版本 
 * 单例
 */

import { CustomAdType } from "./Define";
import utils from "./Utils";



export default class gameShareAdsVideo {
    public static _instance:gameShareAdsVideo = null
    isvideoend: boolean;
    checkVideo: boolean;
    private _type: any;
    isdebug = true    //true 是测试模式  该模式 无广告 无 网络
    public static get Instance(){
        if (null == this._instance) {
            this._instance = new gameShareAdsVideo();
        }
        return this._instance
    }

    //platform:string = 'tt'
    private _platform:string
    get platform():string {
        if(cc.sys.platform == cc.sys.BYTEDANCE_GAME){
            this._platform = 'tt'
            return this._platform
        }else if(cc.sys.platform == cc.sys.WECHAT_GAME){
            this._platform = 'wx'
            return this._platform
        }
    }
    set platform(str){
        this._platform = str
    }

    videoRecordingState:any = 0;
    video_recorder:any = null;
    videoStartTime:any = null;
    videoPath:any = null;
    videoIsExist:any = 0;//视频是否存在 默认存在
    recorderTime:any = 120; //视频录制时间
    videoAd:any = null; //激励视频
    chaPingErr:any = false; //插屏报错（触发频繁限制等）
    chaPing:any = null
    bannerAd:any = null; //横屏广告
    videoCallBack = null //激励视频成功回调
    videoFailCallBack = null //激励视频失败回调
    isshowbanner = false
    //platformSdk:any = tt //字节跳动sdk

    Ad_Custom_DanGe = null              //单个
    Ad_Custom_HengXiang = null          //横向
    Ad_Custom_ShuXiang_R = null         //竖向   靠右边
    Ad_Custom_ShuXiang_L = null         //竖向   靠左边
    Ad_Custom_JuZhen = null             //矩阵    

    wx_info:any = {
        gamename:"",//游戏名称
        shareTitle:'',//分享标题
        appId:'', //appid

        bannerId:"adunit-ae3a557d1b2fb2c4",//横幅 
        videoId2:'adunit-2f4056c40bc7abb4', //激励
        chapingId:'adunit-cb292b2f5571cafb', //插屏
        NativeAd:{ // 原生模板广告
            juzhen:'adunit-3fb31519568c00e7', //九宫格
            heng4:'adunit-5735928f6cb04468',  //横向4个 
            zong4_R:"adunit-3bc1914fd8075d54",  //纵向4个 右
            zong4_L:"adunit-9b733a09d32279f5",  //纵向4个 左
        },

        templateId: ['','','',''],
        videoTopics:['','']
    }

    tt_info:any = {
        gamename:"游戏名称",
        shareTitle:'#分享标题1#分享标题2',
        appId:'ttf7f9814468c8a48702',  
        videoId: 'omf0jln40ha4kd436c',    //激励视频
        chapingId: '30nfue6gfdi1jc60a9', 
        bannerId: "a7fafbe768045fle10",
        templateId: ['','','',''],
        videoTopics:['找茬','找不同'],
        appSecret:'',
    }

    url:string = ''
    web_url = ''
    /**
     * 获取平台 类
     */
     getPlatformClass(){
        var p_class = null
        switch(this.platform){
            case 'tt':
                //@ts-ignore
                p_class = tt
            break
            case 'wx':
                //@ts-ignore
                p_class = wx
            break
        }
        return p_class
    }

    /**
     * 获取分享标题
     */
    getShareTitle(){
        var title = ''
        switch(this.platform){
            case 'tt':
                title = this.tt_info.shareTitle
            break
            case 'wx':
                title = this.wx_info.shareTitle
            break
        } 
        return title
    }

    /**
     * 获取名字
     */
    getName(){
        var name = ''
        switch(this.platform){
            case 'tt':
                name = this.tt_info.gamename
            break
            case 'wx':
                name = this.wx_info.gamename
            break
        } 
        return name
    }

    /**
     * 获取appid 
     */
    getAppId(){
        var appid = ''
        switch(this.platform){
            case 'tt':
                appid = this.tt_info.appId
            break
            case 'wx':
                appid = this.wx_info.appId
            break
        } 
        return appid
    }

    /**
     * 获取AppSecret
     */
     getAppSecret(){
        var appSecret = ''
        return appSecret
    }
    
    /**
     * 获取bannerid
     */
    getBannerId(){
        var bannerID = ''
        switch(this.platform){
            case 'tt':
                bannerID = this.tt_info.bannerId
            break
            case 'wx':
                bannerID = this.wx_info.bannerId
            break
        } 
        return bannerID
    }

    /**
     * 获取videoid
     */
    getVideoId(){
        var videoId = ''
        switch(this.platform){
            case 'tt':
                videoId = this.tt_info.videoId
            break
            case 'wx':
                videoId = this.wx_info.videoId
            break
        } 
        return videoId
    }
    getVideoId2(){
        if(this.platform == 'wx'){
            var videoId = ''
            videoId = this.wx_info.videoId2
            return videoId
        }
    }

    /**
     * 获取id
     * @param {*012} type 
     */
     getNativeAd(type){
        var id = ''
        switch(this.platform){
            case 'wx':
                if(type == CustomAdType.More){
                    id = this.wx_info.NativeAd.juzhen
                }else if(type == 1){
                    id = this.wx_info.NativeAd.heng4
                }else if(type == 2){
                    
                }
            break
        } 
        return id
    }

    /**
     * 获取插屏广告id
     */
    getChaPingId(){
        var chapingId = ''
        switch(this.platform){
            case 'tt':
                chapingId = this.tt_info.chapingId
            break
            case 'wx':
                chapingId = this.wx_info.chapingId
            break
        } 
        return chapingId
    }

    /**
     * 获取分享审核id
     */
    getTemplateId(){
        var templateId = ''
        return templateId
    }

    /**
     * 游戏分享
     */
    game_share(callBack){
        console.log('游戏分享')
        if (cc.sys.platform  === cc.sys.WECHAT_GAME) {
            //console.log('游戏分享')
            this.getPlatformClass().shareAppMessage({
                // templateId: templateId, // 替换成通过审核的分享ID
                // query: "",
                title: '80%老同学都卡在这里了，难道这关就这么难了吗？', 
                imageUrlId: 'vB2VxuHaRdqIQxGytKrYXw==',
                imageUrl: 'https://mmocgame.qpic.cn/wechatgame/fIiaXSY0ANicTRfDr395BbEDT0R54yO9lsUWiasL5Xg8XIcrwUOvqOA0vt6hMOp29tu/0',

                success() {
                  //console.log("分享成功");
                  callBack()
                },
                fail(e) {
                  //console.log("分享失败");
                }
            });
        } else if(cc.sys.platform == cc.sys.BYTEDANCE_GAME_SUB){
            if(this.isdebug) return callBack()
            //console.log('游戏分享')
            var title = this.getShareTitle()
            var templateId = this.getTemplateId()
            this.getPlatformClass().shareAppMessage({
                templateId: templateId, // 替换成通过审核的分享ID
                query: "",
                success() {
                  //console.log("分享成功");
                  callBack()
                },
                fail(e) {
                  //console.log("分享失败");
                }
            });
        }
    }


    /**
     * 分享到好友
     * @param callback 
     */
    shareGameToFriend(callback, note?:string){
        console.log('分享到好友')
        if(this.isdebug) return callback()
        let notestr = '你的好友邀请你一起战斗'
        if(note) notestr = note
        var self = this
        if (cc.sys.platform  === cc.sys.WECHAT_GAME) {
            let title = this.getName()
            this.getPlatformClass().shareAppMessage({
                channel: "invite", // 拉起邀请面板分享游戏好友
                title: title,
                desc: notestr,
                imageUrl: "",
                query: "",
                success() {
                  //console.log("分享成功");
                },
                fail(e) {
                  //console.log("分享失败");
                },
            });
        }else if(cc.sys.platform == cc.sys.BYTEDANCE_GAME){
            if(this.isdebug) return callback()
            let title = this.getName()
            this.getPlatformClass().shareAppMessage({
                channel: "invite", // 拉起邀请面板分享游戏好友
                title: title,
                desc: notestr,
                imageUrl: "",
                query: "",
                success() {
                  //console.log("分享成功");
                },
                fail(e) {
                  //console.log("分享失败");
                },
            });
        }
        
    }

    /**
     *  banner 广告显示
     */
    bannerAds_Show(){
        console.log('banner 广告显示')
        if(this.isdebug) return
        var self = this
        if (cc.sys.platform == cc.sys.BYTEDANCE_GAME) {
            if (self.bannerAd == null) {
                let winSize = this.getPlatformClass().getSystemInfoSync();
                let bannerWidth = winSize.windowWidth;
                let bannerHeight = 100;
                // // 广告
                let bannerID = this.getBannerId()
                self.bannerAd = this.getPlatformClass().createBannerAd({
                    adUnitId: bannerID,
                    style: {
                        left: (winSize.windowWidth - bannerWidth) / 2,
                        top: winSize.windowHeight - bannerHeight,
                        width: bannerWidth,
                        height: bannerHeight,
                    }
                })

                self.bannerAd.onResize(res => {
                    self.bannerAd.style.left = (winSize.windowWidth - res.width) / 2;
                    self.bannerAd.style.top = winSize.windowHeight - res.height ;
                })
                self.bannerAd.onError(function (res) {
                    console.log(res);
                })
            }
            if (self.bannerAd != null) {
                console.log('显示banner')
                self.bannerAd.show();
            }
        }else if(cc.sys.platform  === cc.sys.WECHAT_GAME){
            if (self.bannerAd == null) {
                self.isshowbanner = false
                let winSize = this.getPlatformClass().getSystemInfoSync();
                let bannerWidth:number = winSize.windowWidth;
                let bannerHeight = 100;
                // // 广告
                let bannerID = this.getBannerId()
                self.bannerAd = this.getPlatformClass().createBannerAd({ 
                    adUnitId: bannerID,
                    adIntervals:30,  //自动刷新时间 最少30 。 无，不自动
                    style: {
                        left: (winSize.windowWidth - bannerWidth) / 2,
                        top: winSize.windowHeight - bannerHeight ,
                        width: bannerWidth,
                        height: bannerHeight,
                    }
                })
                self.bannerAd.onResize(res => {
                    self.bannerAd.style.left = (winSize.windowWidth - res.width) / 2;
                    self.bannerAd.style.top = winSize.windowHeight - res.height ;
                })
                self.bannerAd.onError(function (res) {
                    console.log('banner失败',res);
                    self.bannerAd = null
                    //self.bannerAds_Load()
                })
                self.bannerAd.onLoad(() => {
                    console.log('banner 广告加载成功')
                    //gameConfig.isshowbanner = true
                })
            }
            if (self.bannerAd != null) {
                self.bannerAd.show();
            }
        }
    }

    /**
     * banner 广告隐藏
     */
    bannerAds_Hide(){
        console.log('banner 广告隐藏')
        if(this.isdebug) return
        var self = this
        if (cc.sys.platform  === cc.sys.WECHAT_GAME) {
            if (self.bannerAd != null) {
                self.bannerAd.hide();
            }
        }else if(cc.sys.platform == cc.sys.BYTEDANCE_GAME){
            if (self.bannerAd != null) {
                self.bannerAd.hide();
            }
        }
    }

    /**
     * 插屏广告加载
     */
     chaPingAds_Load(){
        console.log('插屏广告加载')
        if(this.isdebug) return
        if(cc.sys.platform == cc.sys.WECHAT_GAME){
            var chapingId = this.getChaPingId()
            this.chaPing = this.getPlatformClass().createInterstitialAd({ adUnitId: chapingId })

            this.chaPing.onError(err => {
                console.log('插屏广告拉取失败',err)
                //gameConfig.chaPing = wx.createInterstitialAd({ adUnitId: chapingId })
            })

        }
    }

    /**
     * 插屏广告显示
     */
    chaPingAds_Show(callback?){
        console.log('插屏广告显示')
        if(this.isdebug) return
        var self = this
        if(cc.sys.platform == cc.sys.WECHAT_GAME){
            
            if(self.chaPingErr == true){
                if(callback){
                    //this.showToast('资源未准备好...')
                    console.log('资源未准备好...')
                    return callback()
                }
                
            } 
            self.chaPingErr = true
            setTimeout(()=>{
                self.chaPingErr = false
            },45000)

            self.chaPing.show()
            .then(()=>{
                if(callback){
                    callback()
                }
                
            })
            .catch((err) => {
                console.error(err)
                //self.showToast('资源未准备好...')
                console.log('展示广告失败')
                if(callback){
                    callback()
                }
                
                //gameConfig.chaPing = wx.createInterstitialAd({ adUnitId: this.getChaPingId() })
            })
        }else if(cc.sys.platform == cc.sys.BYTEDANCE_GAME){         
            let sysData = this.getPlatformClass().getSystemInfoSync()
            if(sysData.appName == 'devtools') return console.log('插屏开发工具不操作')
            if(self.chaPingErr == true) return
            self.chaPingErr = true
            setTimeout(()=>{
                self.chaPingErr = false
            },60000)
            var chapingId = this.getChaPingId()
            if (this.getPlatformClass().createInterstitialAd) {
                const interstitialAd = this.getPlatformClass().createInterstitialAd({
                    adUnitId: chapingId  
                });
                interstitialAd
                    .load()
                    .then(() => {
                        interstitialAd.show();
                    })
                    .catch(err => {
                        console.log(err);
                        setTimeout(() => {
                            interstitialAd.load().then(()=>{interstitialAd.show})
                        }, 5);
                        
                    });
                interstitialAd.onClose(()=>{
                    if(interstitialAd){
                        interstitialAd.destroy()
                    }
                })
            }
        }
    }

    /**
     * 创建原生广告模板
     * @param {0:单个，1：横向多个，2：竖向多个，3：矩阵} type 
     */
     createCustomAd(type){
        if(cc.sys.platform == cc.sys.WECHAT_GAME){//微信
            console.log('创建原生广告type=', type)
            let inifo = this.getPlatformClass().getSystemInfoSync()
            if(utils.compareVersion( inifo.SDKVersion ,'2.11.1')>= 0){
                if(type == CustomAdType.One){ //单个
                    //常规样式默认画布为 60×104 像素
                    //卡片样式默认画布为 68×106 像素
                }else if(type == CustomAdType.Heng){ //横向 顶部 水平布局默认画布为 360×106 像素
                    let adWidth = 360;
                    let adHeight = 110;
                    let id = this.getNativeAd(type)
                    this.Ad_Custom_HengXiang = this.getPlatformClass().createCustomAd({
                        adUnitId: id,
                        adIntervals:35,
                        style: {
                            left: (inifo.screenWidth - adWidth)/2,
                            top: inifo.screenHeight - adHeight,
                            fixed:false
                        }
                    })
                    this.Ad_Custom_HengXiang.onLoad((res)=>{
                        console.log('横向原生广告加载', res)
                    })
                    this.Ad_Custom_HengXiang.onError((res)=>{
                        console.log('横向原生广告报错', res)
                    })
                    this.Ad_Custom_HengXiang.onHide((res)=>{
                        console.log('横向原生监听关闭')
                    })
                }else if(type == CustomAdType.Shu){  //竖向 左右 垂直布局默认画布为 72×410 像素
                    let adWidth = 72 
                    let adHeight = 410
                    let id_r = this.wx_info.NativeAd.zong4_R
                    this.Ad_Custom_ShuXiang_R = this.getPlatformClass().createCustomAd({
                        adUnitId: id_r,
                        adIntervals:35,
                        style: {
                            left: (inifo.screenWidth - adWidth),
                            top: inifo.screenHeight - adHeight,
                            fixed:false
                        }
                    })

                    let id_L = this.wx_info.NativeAd.zong4_L
                    this.Ad_Custom_ShuXiang_L = this.getPlatformClass().createCustomAd({
                        adUnitId: id_L,
                        adIntervals:35,
                        style: {
                            left: 0,
                            top: inifo.screenHeight - adHeight,
                            fixed:false
                        }
                    })

                    
                }else if(type == CustomAdType.More){ //矩阵
                    // 2×5 布局默认画布为 360×188 像素
                    // 5×5 布局默认画布为 360×352 像素  
                    let adWidth = 360;
                    let adHeight = 500;
                    let id = this.getNativeAd(type)
                    this.Ad_Custom_JuZhen = this.getPlatformClass().createCustomAd({
                        adUnitId: id,
                        adIntervals:35,
                        style: {
                            left: (inifo.screenWidth - adWidth)/2,
                            top: (inifo.screenHeight - adHeight)/2,
                            fixed:false
                        }
                    })
                    this.Ad_Custom_JuZhen.onLoad((res)=>{
                        //console.log('矩阵原生广告加载', res)
                    })
                    this.Ad_Custom_JuZhen.onError((res)=>{
                        //console.log('矩阵原生广告报错', res)
                    })
                    this.Ad_Custom_JuZhen.onHide((res)=>{
                        //console.log('矩阵原生监听关闭')
                    })
                }
            }
        }
    }

    /**
     * 展示 
     * @param {*} ad 
     */
    showCustomAd(type){
        if(cc.sys.platform == cc.sys.WECHAT_GAME){//微信
            console.log('展示原生广告', type)
            switch(type){
                case 0:
                break
                case CustomAdType.Heng:
                    this.Ad_Custom_HengXiang.show()
                break
                case CustomAdType.Shu:
                    this.Ad_Custom_ShuXiang_R.show()
                    this.Ad_Custom_ShuXiang_L.show()
                break
                case CustomAdType.More:
                    this.Ad_Custom_JuZhen.show()
                break
            }
        }
    }

    /**
     * 隐藏, 销毁原生广告模板
     */
    hideCustomAd(type){
        if(cc.sys.platform == cc.sys.WECHAT_GAME){//微信
            console.log('关闭原生广告',type)
            switch(type){
                case 0:

                break
                case CustomAdType.Heng:
                    this.Ad_Custom_HengXiang.hide()
                break
                case CustomAdType.Shu:
                    this.Ad_Custom_ShuXiang_R.hide()
                    this.Ad_Custom_ShuXiang_L.hide()
                break
                case CustomAdType.More:
                    this.Ad_Custom_JuZhen.hide()
                break
            }
        }
    }

    /**
     * 激励广告加载
     */
     motivational_Video_Load(){
        console.log('激励广告加载')
        if(this.isdebug) return
        if(cc.sys.platform == cc.sys.WECHAT_GAME){
            var self = this
            var videoId = this.getVideoId2()
            self.videoAd = this.getPlatformClass().createRewardedVideoAd({
                adUnitId: videoId,
                //multiton: true
            })
            self.videoAd.onError((res)=>{
                console.log('激励视频错误',res)
            })
            self.videoAd.load()

            var endCallBack = function(res){
                if (res.isEnded == true) {
                    if(self.videoCallBack != null){
                        console.log('获取奖励')
                        self.videoCallBack()
                    }
                    
                    if(this._type != -1){
                        self.showToast('已获得')
                    }
                } else {
                    if (self.videoFailCallBack != null) self.videoFailCallBack() 
                }
                
                self.isvideoend = true

                setTimeout(()=>{
                    self.checkVideo = false
                },60000)
                
            }
            self.videoAd.onClose(endCallBack); //绑定结束回调
        }else if(cc.sys.platform == cc.sys.BYTEDANCE_GAME){
            let sysData = this.getPlatformClass().getSystemInfoSync()
            if(sysData.appName == 'devtools') return console.log('开发工具不操作')

            var self = this
            var videoId = this.getVideoId()
            this.videoAd = this.getPlatformClass().createRewardedVideoAd({
                adUnitId: videoId,
                //multiton: true
            })
            this.videoAd.onError((res)=>{
                //console.log('激励视频错误',res)
            })
            this.videoAd.load()

            var endCallBack = function(res){
                if (res.isEnded == true) {
                    if(self.videoCallBack != null){
                        //console.log('获取奖励')
                        self.videoCallBack()
                    }
                    
                    if(this._type != -1){
                        self.showToast('已获得')
                    }
                } else {
                    if (self.videoFailCallBack != null) self.videoFailCallBack() 
                }
                
                self.isvideoend = true
            }
            self.videoAd.onClose(endCallBack); //绑定结束回调
        }
    }

    /**
     * 展示激励视频 
     * 参数1 成功回调
     * 参数2 失败回调 可以省略
     */
     motivational_Video_Show(success, faile, type?){
        console.log('展示激励视频')
        if(this.isdebug) return success()
        var self = this
        if(this.checkVideo == true) return this.showToast('勿频繁点击')
            
        setTimeout(()=>{
            self.checkVideo = false
        },1000)

        this.videoCallBack = success
        this.videoFailCallBack = faile
        this._type = type
        if(cc.sys.platform == cc.sys.WECHAT_GAME){ //微信
            this._type = type

            if(self.videoAd == null || self.videoAd == undefined){
                return this.videoCallBack()
            }
            

            self.videoAd.onError((res)=>{
                console.log('广告出错监听', res)
            })

            // /**展示 */
            self.videoAd
                .show()
                .then(() => {
                })
                .catch(err => {
                    self.showToast('激励视频播放失败')
                    console.log('打印激励视频错误', err)
                    // 可以手动加载一次
                    self.videoAd.load().then(() => {
                    // 加载成功后需要再显示广告
                    return self.videoAd.show();
                    });
                });
        }else if(cc.sys.platform == cc.sys.BYTEDANCE_GAME){ 
            this.checkVideo = true
            let sysData = this.getPlatformClass().getSystemInfoSync()
            if(sysData.appName == 'devtools') return success(),console.log('开发工具不操作')
            if(this.videoAd == null || this.videoAd == undefined){
                return this.videoCallBack()
            }
            this.videoAd.onError((res)=>{
                //console.log('广告出错监听', res)
            })
            // /**展示 */
            this.videoAd
                .show()
                .then(() => {
                })
                .catch(err => {
                    self.showToast('激励视频播放失败')
                    //console.log('打印激励视频错误', err)
                    // 可以手动加载一次
                    self.videoAd.load().then(() => {
                    // 加载成功后需要再显示广告
                    return self.videoAd.show();
                    });
                });
        }
        else{
            self.videoCallBack()
        }
    }

    

    /**
     * 录制视频开始
     */
    recording_Video_Start(){
        console.log('录制视频开始')
        if(this.isdebug) return 
        var self = this
        
        if (cc.sys.platform == cc.sys.BYTEDANCE_GAME) {
            let sysData = this.getPlatformClass().getSystemInfoSync()
            if(sysData.appName == 'devtools') return console.log('开发工具不操作')
            self.videoRecordingState = 1;
            self.videoIsExist = 0;
            self.video_recorder = this.getPlatformClass().getGameRecorderManager();
    
            self.videoStartTime = Date.parse(new Date().toString()) //Date.parse(new Date());
            //开始回调
            self.video_recorder.onStart(res => {
                //console.log('录屏开始');
                //console.log(res);
            });
            //开始
            self.video_recorder.start({
                duration: self.recorderTime, //录制时长
            });
            //录制结束回调
            self.video_recorder.onStop(res => {
                self.videoRecordingState = 2;
                self.videoPath = res.videoPath;
                //console.log('录屏结束', self.videoPath)
                // do somethine;
            });
            //录制错误回调
            self.video_recorder.onError(res => {
                //console.log("录屏error", res)
            });
        }
    }

    /**
     * 录制视频结束
     */
    recording_Video_End(){
        console.log('录制视频结束')
        if(this.isdebug) return
        if (cc.sys.platform == cc.sys.BYTEDANCE_GAME) {
            let sysData = this.getPlatformClass().getSystemInfoSync()
            if(sysData.appName == 'devtools') return console.log('开发工具不操作')
            var self = this
            //console.log('录屏结束');
            //gameConfig.shareVideoTips = 0;
            if (self.video_recorder) {
                var endTime = Date.parse(new Date().toString())  //Date.parse(new Date());
                if ((endTime - self.videoStartTime) / 1000 <= 5) {
                    self.videoIsExist = 1;
                }else{
                    self.videoIsExist = 0;
                }
                self.video_recorder.stop();
            }
        }
    }

    /**
     * 录制视频分享
     * 参数1 成功回调方法
     * 参数2 失败回调方法
     */
    recording_Video_Share(callBack, failCallBack){
        console.log('录制视频分享')
        if(cc.sys.platform == cc.sys.WECHAT_GAME){
            this.game_share(()=>{})
            callBack()
        }else if(cc.sys.platform == cc.sys.BYTEDANCE_GAME){
            if(this.isdebug) return callBack()
            let sysData = this.getPlatformClass().getSystemInfoSync()
            if(sysData.appName == 'devtools') return console.log('开发工具不操作')
            var self = this
            if(self.videoIsExist == 1){
                self.showToast('录制时间过短')
                return;
            }
            var result = 200;
            self.videoRecordingState = 3;
            this.getPlatformClass().shareAppMessage({
                channel: 'video',
                title: '',
                imageUrl: '',
                query: '',
                extra: {
                    videoPath: self.videoPath, // 可用录屏得到的视频地址
                    videoTopics: self.tt_info.videoTopics,
                    createChallenge: true
                },
                success() {
                    self.showToast('分享视频成功')
                    callBack()
                    //self.recording_Video_Start()
                },
                fail(e) {
                    result = 201;
                    self.showToast('分享视频失败')
                    //console.log('分享失败', e)
                    failCallBack()
                    //self.recording_Video_Start()
                }
            })
        }
        else{
            callBack()
        }
    }

    //录屏是否存在
    getVideoIsExist(){
        return this.videoIsExist
    }

    /**
     * 添加桌面
     * @param scb 
     * @param fcb 
     */
    addShortcut(scb:Function, fcb:Function){
        if(this.isdebug) return scb()
        this.getPlatformClass().addShortcut({
            success() {
                this.showToast("添加桌面成功");
                scb()
            },
            fail(err) {
                this.showToast("添加桌面失败");
                fcb()
            },
        });
    }
    /**
     * 检测是否添加到桌面 
     * @returns true 不支持 或者 已添加
     */
    checkShortcut(){
        if(this.isdebug) return
        if((cc.sys.platform == cc.sys.WECHAT_GAME || cc.sys.platform == cc.sys.BYTEDANCE_GAME) && cc.sys.os == cc.sys.OS_ANDROID){
            const version = this.getPlatformClass().getSystemInfoSync().SDKVersion
            if (utils.compareVersion(version, '2.46.0') >= 0) {
                this.getPlatformClass().checkShortcut({
                    success(res) {
                        let exist = res.status.exist
                        //console.log("检查快捷方式", res.status);
                        return exist
                    },
                    fail(res) {
                        return true
                        //console.log("检查快捷方式失败", res.errMsg);
                    },
                });
            }else{
                return true
            }
        }else{
            return true
        }
    }

    /**
     * 提示框
     */
    showToast(str){
        if (cc.sys.platform  === cc.sys.WECHAT_GAME) {
            this.getPlatformClass().showToast({
                title: str,
                duration: 1000,
                success(res) {
                //console.log(`${res}`);
                },
                fail(res) {
                //console.log(`showToast调用失败`);
                }
            });
        }else{
            console.log(str)
        }
    }

    /**
     * 获取不重复的随机数
     * @param minValue 最小值
     * @param maxValue 最大值
     * @param valueNum 随机个数
     */
    getRandomValueDif(minValue, maxValue, valueNum) {
        // 全部随机数值  
        let allNums = new Array;

        // 判断获取随机数个数  
        let size = valueNum ? (valueNum > maxValue - minValue + 1 ? maxValue - minValue + 1 : valueNum) : 1;

        // 生成随机数值区间数组  
        for (let i = minValue, k = 0; i <= maxValue; i++ , k++) {
            allNums[k] = i;
        }

        let arr = []

        // 随机从数组里面取值
        allNums.sort(function () { return 0.5 - Math.random(); });
        for (let j = 0; j < size; j++) {
            let index = Math.floor(Math.random() * allNums.length);
            arr.push(allNums[index]);
            let tmp = allNums[index];
            allNums[index] = allNums[allNums.length - 1];
            allNums[allNums.length - 1] = tmp;
            allNums.pop();
        }

        return arr;
    }

    /**
     * 获取范围内的随机数
     * @param minValue 最小值
     * @param maxValue 最大值
     */
    getRangeRandom(minValue, maxValue) {
        // 获取数组从第一个开始到指定个数的下标区间  
        return this.getRandomValueDif(minValue, maxValue, 1)[0];
    }

    vibrateShort(){
        if(cc.sys.platform == cc.sys.WECHAT_GAME || cc.sys.platform == cc.sys.BYTEDANCE_GAME){
            this.getPlatformClass().vibrateShort()
        }
    }


    /**
     * 设置 抖音排行榜  数字类型排行榜
     * @param value     数值
     */
    setImRankData_Num(value:string){
        if(this.isdebug) return
        if(cc.sys.platform == cc.sys.BYTEDANCE_GAME){
            //@ts-ignore
            const sysinfo = tt.getSystemInfoSync()
            const sdkversion = sysinfo.SDKVersion
            let appname = sysinfo.appName
            let appVersion = sysinfo.version
            if (utils.compareVersion(sdkversion, '2.70.0') >= 0
                && (appname == 'Douyin' || appname == 'douyin_lite')
                && utils.compareVersion(appVersion, '23.2.0') >= 0) {
                //@ts-ignore
                tt.setImRankData({
                    dataType: 0, //成绩为数字类型
                    value: "" + value, //该用户得了999999分
                    priority: 0, //dataType为数字类型，不需要权重，直接传0
                    extra: "extra",
                    success(res) {
                      console.log(`setImRankData success res: ${res}`);
                    },
                    fail(res) {
                      console.log(`setImRankData fail res: ${res.errMsg}`);
                    },
                  });
            }
        }
    }
    /**
     * 获取数字类型原生排行榜
     */
    getImRankList_Num(){
        if(this.isdebug) return
        if(cc.sys.platform == cc.sys.BYTEDANCE_GAME){
            //@ts-ignore
            const sysinfo = tt.getSystemInfoSync()
            const sdkversion = sysinfo.SDKVersion
            let appname = sysinfo.appName
            let appVersion = sysinfo.version
            if (utils.compareVersion(sdkversion, '2.70.0') >= 0
                && (appname == 'Douyin' || appname == 'douyin_lite')
                && utils.compareVersion(appVersion, '23.2.0') >= 0) {
                //@ts-ignore
                tt.getImRankList({
                    relationType: "default", //只展示好友榜
                    dataType: 0, //只圈选type为数字类型的数据进行排序
                    rankType: "day", //每月1号更新，只对当月1号到现在写入的数据进行排序
                    suffix: "关", //数据后缀，成绩后续默认带上 “分”
                    rankTitle: "游戏排行榜", //标题
                    success(res) {
                      console.log(`getImRankData success res: ${res}`);
                    },
                    fail(res) {
                      console.log(`getImRankData fail res: ${res.errMsg}`);
                    },
                  });
            }else{
                this.showToast('app版本不支持该功能')
            }
        }
        
    }


    /**
     * 设置 抖音排行榜  枚举类型排行榜
     * @param value     数值
     * @param priority  权重
     */
     setImRankData_Enum(value:string,priority:number){
        if(this.isdebug) return
        if(cc.sys.platform == cc.sys.BYTEDANCE_GAME){
            //@ts-ignore
            const sysinfo = tt.getSystemInfoSync()
            const sdkversion = sysinfo.SDKVersion
            let appname = sysinfo.appName
            let appVersion = sysinfo.version
            if (utils.compareVersion(sdkversion, '2.70.0') >= 0
                && (appname == 'Douyin' || appname == 'douyin_lite')
                && utils.compareVersion(appVersion, '23.2.0') >= 0) {
                //@ts-ignore
                tt.setImRankData({
                    dataType: 1, //成绩为枚举类型，因为段位不是一个数字
                    value: "" + value, //该用户段位为白银
                    priority: priority, //dataType为枚举类型，需要权重，该游戏排序为 青铜（1）、白银（2）、黄金（3）、王者（4），因此此处传2
                    extra: "extra",
                    success(res) {
                      console.log(`setImRankData success res: ${res}`);
                    },
                    fail(res) {
                      console.log(`setImRankData fail res: ${res.errMsg}`);
                    },
                  });
            }

        }
    }
    /**
     * 获取枚举类型原生排行榜
     */
     getImRankList_Enum(){
        if(this.isdebug) return
        if(cc.sys.platform == cc.sys.BYTEDANCE_GAME){
            //@ts-ignore
            const sysinfo = tt.getSystemInfoSync()
            const sdkversion = sysinfo.SDKVersion
            let appname = sysinfo.appName
            let appVersion = sysinfo.version
            if (utils.compareVersion(sdkversion, '2.70.0') >= 0
                && (appname == 'Douyin' || appname == 'douyin_lite')
                && utils.compareVersion(appVersion, '23.2.0') >= 0) {
                //@ts-ignore
                tt.getImRankList({
                    relationType: "default", //好友榜、总榜都展示
                    dataType: 1, //只圈选type为枚举类型的数据进行排序
                    rankType: "day", //每天凌晨0点更新，只对当天0点到现在写入的数据进行排序
                    suffix: "", //为空或不填，一般枚举类型不需要填后缀
                    rankTitle: "游戏排行榜", //标题
                    success(res) {
                      console.log(`getImRankData success res: ${res}`);
                    },
                    fail(res) {
                      console.log(`getImRankData fail res: ${res.errMsg}`);
                    },
                  });
            }else{
                this.showToast('app版本不支持该功能')
            }
        }
    }

    /**
     * 上传微信 游戏得分
     */
    upWxHighScore(score, callBack){
        if(cc.sys.platform == cc.sys.WECHAT_GAME){
            //@ts-ignore
            wx.setUserCloudStorage({
                KVDataList: [{key: 'checkout', value: String(score)}],
                success: res => {
                    console.log('上传排行数据success',res);
                    // // 让子域更新当前用户的最高分，因为主域无法得到getUserCloadStorage;
                    // let openDataContext = wx.getOpenDataContext();
                    // openDataContext.postMessage({
                    //     type: 'updateMaxScore',
                    // });
                    callBack()
                },
                fail: res => {
                    console.log('上传排行数据fail',res);
                }
            });
        }
    }
}
